package com.bayvakoof.dewall.geom
{
	import flash.geom.Point;

	public class GeometricUtil
	{
		private static const TOLERANCE:Number = 0.001;
		
		/**
		 * test three point is collinear
		 * */
		public static function collinear(x1:Number, y1:Number, x2:Number, y2:Number, x3:Number, y3:Number):Boolean
		{
			var result:Number = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1);
			return Math.abs(result) < TOLERANCE;
		}
		
		/**
		 * point in polygon
		 * */
		public static function pnpoly(polygon:Vector.<Point>, p:Point):Boolean
		{
			/*var counter:int = 0;
			var i:int;
			var xinters:Number;
			var p1:Point;
			var p2:Point;
			var N:int = polygon.length;
			
			p1 = Point(polygon[0]);
			for (i=1;i<=N;i++) {
				p2 = polygon[i % N];
				if (p.y > Math.min(p1.y,p2.y)) {
					if (p.y <= Math.max(p1.y,p2.y)) {
						if (p.x <= Math.max(p1.x,p2.x)) {
							if (p1.y != p2.y) {
								xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
								if (p1.x == p2.x || p.x <= xinters)
									counter++;
							}
						}
					}
				}
				p1 = p2;
			}
			
			if (counter % 2 == 0)
				return false;
			else
				return true;*/
			
			var i:int, j:int=polygon.length - 1 ;
			var oddNodes:Boolean=false;
			
			for (i=0; i<polygon.length; i++) {
				if ((polygon[i].y < p.y && polygon[j].y >= p.y
					||   polygon[j].y < p.y && polygon[i].y >= p.y)
					&&  (polygon[i].x <= p.x || polygon[j].x <= p.x)) {
					if(polygon[i].x+(p.y-polygon[i].y)/(polygon[j].y-polygon[i].y)*(polygon[j].x-polygon[i].x)<p.x)
						oddNodes = !oddNodes;
				}
				j=i;
			}
			
			return oddNodes;
		}
		
		public static function pnpolys(polygons:Vector.<Vector.<Point>>, p:Point):Boolean
		{
			var oddNodes:Boolean=false;
			
			for each(var polygon:Vector.<Point> in polygons)
			{
				var i:int, j:int=polygon.length - 1 ;
				
				for (i=0; i<polygon.length; i++) {
					if ((polygon[i].y < p.y && polygon[j].y >= p.y
						||   polygon[j].y < p.y && polygon[i].y >= p.y)
						&&  (polygon[i].x <= p.x || polygon[j].x <= p.x)) {
						if(polygon[i].x+(p.y-polygon[i].y)/(polygon[j].y-polygon[i].y)*(polygon[j].x-polygon[i].x)<p.x)
							oddNodes = !oddNodes;
					}
					j=i;
				}
			}
			return oddNodes;
		}
	}
}